#ifndef __WMYSQL_H__
#define __WMYSQL_H__

#include "common/env.h"
#include "common/bytearrays.h"
#include "common/msgmacro.h"
#include "common/msghandle.h"
#include "common/msgqueue.h"
#include "common/msgclass.h"
#include "common/output.h"
#include "common/section.h"
#include "common/memorypool.h"
#include "common/timecallback.h"

using namespace WServer;
using namespace WServer::Env;
using namespace WServer::GData;
using namespace WServer::MsgHandle;
using namespace WServer::MsgQueue;
using namespace WServer::Output;
using namespace WServer::Section;

extern void OnMySQLStarted(int inc);
extern void HandleMessage(struct wmsgdata* msg);
extern void initPlayerData(int clientindex, int dbid);
extern void updatePlayerData(int clientindex, std::string tname, int dbid, std::string cmd);
extern void insertPlayerData(int clientindex, std::string tname, int dbid);
extern void savePlayerData(int clientindex);
extern void removePlayerData(int clientindex);

namespace WServer {
namespace MySQL {
extern std::vector<MYSQL> mysql;
extern pthread_mutex_t* mysqllock;

class WRecordset {
public:
	MYSQL* mysql;
	MYSQL_RES* pRecordset;
	std::map<std::string, unsigned int> fieldNameIndexMap;
	int recordCount;

	WRecordset() {
		pRecordset = NULL;recordCount = 0;
	}
	void SetRecordset(MYSQL* pmysql) {
		mysql = pmysql;
		pRecordset = mysql_store_result(pmysql);
		if (pRecordset) {
			recordCount = mysql_num_rows(pRecordset);
			MYSQL_FIELD* fields = mysql_fetch_fields(pRecordset);

			for (int i = 0; i < mysql_num_fields(pRecordset); i++) {
				fieldNameIndexMap[fields[i].name] = i;
			}
			mysql_data_seek(pRecordset, 0);
			mysql_fetch_row(pRecordset);
		}
	}

	int IsEOF() {
		return (pRecordset == NULL || pRecordset->current_row == NULL);
	}
	void MovetoNextRow() {
		if (pRecordset) {
			mysql_fetch_row(pRecordset);
	}
	}

	std::string GetFieldValue(int index) {
		if (pRecordset == NULL) {
			return NULL;
		}
		if (index > pRecordset->field_count) {
			return NULL;
		}
		return pRecordset->current_row[index];
	}

	~WRecordset() {
		if (pRecordset) {
			mysql_free_result(pRecordset);
			pRecordset = NULL;
		}
	}
};

bool ConnectDatabase(const char* host, const char* user, const char* password, const char* db);
bool CloseDB();
WRecordset* ExecuteQueryCmd(const char* sqlcommend);
bool ExecuteSQLCmd(const char* sqlcommend);
void FreeRecordset(WRecordset*& record);
int findFreeMysql();
void releaseMysql(int inc);
}
}

#endif //__WMYSQL_H__
